/**
 *dell
 */
'use strict';
const path = require('path');
const fs = require('fs');
let actionBase = path.join(__dirname, '../server/actions/exportExcel/');

module.exports = async function (ctx) {
    let params = ctx.method === 'GET' ? ctx.query : ctx.request.fields;
    let { actionType, special, fileName } = params;
    try {
        if (!special) {
            let execute = require(path.join(actionBase, `${actionType}Action`));
            const workbook = await execute(params);
            const tempExcelPath = `export/${fileName}`;
            await workbook.xlsx.writeFile(tempExcelPath);
            ctx.set('Content-type', 'application/xlsx');
            ctx.attachment(fileName);
            ctx.body = fs.createReadStream(tempExcelPath);
            let rainfallTimeout = setTimeout(function () {
                fs.unlink(tempExcelPath, function (error) {
                    if (error) {
                        return false;
                    }
                });
                clearTimeout(rainfallTimeout)
            }, 60000);

        } else {
            ctx.body = { success: false, message: '未定义可调用函数' };
        }

    } catch (e) {
        ctx.body = { success: false, message: e.message };
    }

};
